import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { compListConfig, compFormConfig } from '@/components/layout/config'
type upType = 'add' | 'replace' | 'delete' | 'clear';
interface upParams {
  index: number,
  endIndex?: number,
  comp?: string
}
export const useCompStore = defineStore('configComp', () => {
  const currCompName = ref<string | null>(null)
  const currCompIndex = ref()
  const compList = ref<any[]>([null, null, null, null, null , null])
  // 当前组件数据
  const compInfo = computed(()=>{
    return compList.value[currCompIndex.value]
  })
  // 当前组件表单配置
  const compForm = computed(()=>{
    return compFormConfig.find((item:any) => item.comp === currCompName.value)?.formConfig
  })
  // 更新组件列表
  function updateCompList(type: upType, params:upParams ) {
    switch(type) {
      case 'add': {
        if(!params.comp) return
        const info = compListConfig.find((item:any) => item.comp === params.comp)
        compList.value.splice(params.index, 1, info)
        break;
      }
      case 'replace':{
        if(params.endIndex || params.endIndex === 0) 
        compList.value[params.index]  = compList.value.splice(params.endIndex, 1, compList.value[params.index])[0]
        break;
      }
      case 'delete':
        compList.value[params.index] = null
        break;
      case 'clear':
        compList.value = [null, null, null, null, null , null]
        break;
    }
  }
  // 更新组件配置
  function updateCompInfo(index: number, configComp: any){
    compList.value[index] = configComp
  }
  return { currCompName, currCompIndex, compInfo, compForm, compList,  updateCompList, updateCompInfo }
},{
  persist: true
})
